package com.lopo.in18;

import com.lopo.pagehelper.Response;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.util.Locale;
import java.util.Objects;

/**
 * @author JCccc
 */
@Aspect
@Component
@Slf4j
public class LanguageAspect {
    @Autowired
    private HttpServletRequest request;
    @Autowired
    private MessageSource messageSource;

    @Pointcut("execution(* com.lopo.*.controller..*(..))")
    public void annotationLangCut() {
    }

    /**
     * 拦截controller层返回的结果，修改msg字段
     *
     * @param point
     * @param resultObject
     */
    @AfterReturning(pointcut = "annotationLangCut()", returning = "response")
    public void around(JoinPoint point, Response response) {
        final String language = request.getParameter("lang");
        Locale locale = Objects.nonNull(language) ? new Locale(language) : Locale.getDefault();
        try {
            if (StringUtils.isNotBlank(response.getMsg())) {
                final String message = messageSource.getMessage(response.getMsg(), null, locale);
                response.setMsg(message);
            }
        } catch (Exception e) {
            log.warn("本地化异常消息发生异常: {}", e);
        }
    }
}